<?php

namespace app\api\controller\ai;

use app\api\logic\OrderLogic;
use app\common\controller\AdminBase;
use app\common\controller\UserBase;
use app\common\model\AiOrder;
use app\common\model\OrderOrder;
use app\common\model\OrderOther;
use app\common\model\SignLog;
use think\db\Query;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class Order extends UserBase
{
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new \app\common\model\AiOrder();
    }

    public function create()
    {
        $data = input();
        $data['user_id'] = $this->uid;
        $rule = [
            "prompt|咒语" => "require",
            "size|尺寸" => "require",
            "n|数量" => "require"
        ];
        Db::startTrans();
        try {
            $this->validate($data, $rule);
            $exit = AiOrder::where('user_id',$this->uid)
                ->whereDay('create_time')
                ->find();
            if (!$exit) {
                $this->user->setInc('xianqi',1);
                $singLog = SignLog::where("user_id",$this->uid)
                    ->whereDay('create_time')
                    ->find();
                if (!$singLog) {
                    SignLog::create([
                        "user_id" => $this->uid,
                        "create" => 1,
                        "create_time" => time()
                    ]);
                } else {
                    $singLog->create = 1;
                    $singLog->save();
                }
            }
            $order = OrderLogic::create($data);
            Db::commit();
            $this->success($order);
        } catch (Exception | ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    public function getDetail()
    {
        $id = input('id/d');
        $order = OrderLogic::getDetail($id);
        $this->success($order);
    }

    // 退款
    public function orderReturned()
    {
        \app\common\model\Order::where("id",$this->data['id'])
            ->save([
                "no_why" => $this->data['no_why'],
                "return_money" => $this->data['return_money'],
                "status" => $this->data['status']
            ]);
        $this->success();
    }
}